package threadcordknowleadge.threadcoreknowledge;

/**
 * @author Brook
 * 两个线程交替打印0~100的奇偶数，用synchronized关键字实现
 */
public class WaitNotifyPrint0ddEvenSyn {
    //新建2个线程
    //第一只处理偶数，第二个只处理奇数，（用位运算）
    //用synchronization来通信

    public static Object lock = new Object();
    public static int count;

    public static void main(String[] args) {
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                   while (count < 100) {
                       synchronized (lock) {
                           if ((count & 1) == 0) {
                               System.out.println(Thread.currentThread().getName()+ count);
                               count++;
                           }
                   }
                }
            }
        }, "偶数ssss");


        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (count < 100) {
                    synchronized (lock) {
                        if ((count & 1) == 1) {
                            System.out.println(Thread.currentThread().getName()+ count);
                            count++;
                        }
                    }
                }
            }
        },"奇数ssss");

        thread1.start();
        thread2.start();
    }

}
